package com.jmb.api.web.custom.interceptor;

import com.jmb.api.common.login.LoginUser;
import com.jmb.api.common.login.LoginUserHolder;
import com.jmb.api.common.utils.JwtUtil;
import com.jmb.api.entity.LogInfoVo;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    /**
     * 拦截器
     * @param request 请求
     * @param response 响应
     * @param handler 处理器
     * @return 拦截结果
     * @throws Exception 抛出异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        Claims claims = JwtUtil.parseToken(token);
        Integer userIdInt = claims.get("userId", Integer.class);
        long userId = userIdInt != null ? userIdInt.longValue(): null;
        String username = claims.get("username", String.class);
        LoginUserHolder.setLoginUser(new LoginUser(userId,username));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserHolder.clear();
    }
}
